package com.weixing.mall.provider.support.excel.ads;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.fastjson.JSON;
import com.google.common.collect.Lists;
import com.weixing.mall.base.exception.BusinessException;
import com.weixing.mall.provider.model.domain.MediaAdvertsing;
import com.weixing.mall.provider.service.IMediaAdvertsingService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;

/**
 * 广告数据导入（更新标题、阅读数量、粉丝数量）
 */
public class AdsImportListener extends AnalysisEventListener<AdsExcalData> {

    private static final Logger LOGGER = LoggerFactory.getLogger(AdsImportListener.class);

    /**
     * 每隔5条存储数据库，实际使用中可以3000条，然后清理list ，方便内存回收
     */
    private static final int BATCH_COUNT = 5;

    List<AdsExcalData> list = Lists.newArrayList();

    private IMediaAdvertsingService mas;

    public AdsImportListener(IMediaAdvertsingService mas){
        this.mas = mas;
    }

    @Override
    public void invoke(AdsExcalData data, AnalysisContext analysisContext) {
        LOGGER.info("解析到一条数据:{}", JSON.toJSONString(data));
        list.add(data);
        //这里暂时不启用
        /*if (list.size() >= BATCH_COUNT) {
            saveData();
            list.clear();
        }*/
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        saveData();
        LOGGER.info("所有数据解析完成！");
    }

    public void saveData() {
        LOGGER.info("{}条数据，开始存储数据库！", list.size());
        if(list.size() ==0 ){
            throw new BusinessException("导入数据为空");
        }
        //待更新数据
        List<MediaAdvertsing> updateList = Lists.newArrayList();
        list.forEach(aed ->{
            if(aed.getId() != null){
                MediaAdvertsing ma = new MediaAdvertsing();
                ma.setId(aed.getId());
                ma.setArticleTitle(aed.getTitle());
                ma.setReadAmount(aed.getReadNum());
                ma.setFans(aed.getFans());
                updateList.add(ma);
            }
        });
        if(!updateList.isEmpty()){
           mas.updateBatchById(updateList);
        }
        LOGGER.info("存储数据库成功！");
    }
}
